import sys

import pandas as pd
import numpy as np
from orbitP.script import config
from scipy.signal import savgol_filter
from statsmodels.tsa.stattools import adfuller, acf
from tqdm import tqdm

def calculate_noise(y, window_size=15, method='savgol'):
    """
    计算时序数据的噪声成分
    参数:
        y : 输入时序数据 (1D数组)
        window_size : 平滑窗口大小 (奇数)
        method : 平滑方法 ('savgol'或'ma')
    返回:
        noise : 噪声序列
        noise_properties : 包含统计指标的字典
    """
    if len(y) < window_size:
        window_size = len(y)
    # 1. 去趋势处理
    if method == 'savgol':
        y_smooth = savgol_filter(y, window_length=window_size, polyorder=2)
    elif method == 'ma':
        y_smooth = np.convolve(y, np.ones(window_size) / window_size, mode='same')
    else:
        raise ValueError("Method must be 'savgol' or 'ma'")

    # 2. 计算噪声
    noise = y - y_smooth

    # 3. 计算噪声特性
    noise_properties = {
        'std': np.std(noise),
        'mean': np.mean(noise),
        'adf_pvalue': adfuller(noise),  # 平稳性检验
        'acf1': acf(noise, nlags=1)[1],  # 一阶自相关
        'skewness': pd.Series(noise).skew(),
        'kurtosis': pd.Series(noise).kurtosis()
    }

    return noise, noise_properties

def calculate_correlate(obs,pred):
    cross_corr = np.correlate(obs, pred, mode='valid')[0]
    return cross_corr


if __name__ == '__main__':
    input_size = 9
    df_ObserData = pd.read_csv(config.dataSetDir + 'df_ObserData.csv')
    df_MOEORBData = pd.read_csv(config.dataSetDir + 'df_MOEORBData.csv')
    df_stampObser = pd.read_csv(config.dataSetDir + 'df_stampObser.csv')
    df_stampMOEORB = pd.read_csv(config.dataSetDir + 'df_stampMOEORB.csv')
    ObserData = df_ObserData.to_numpy()[:, :input_size]
    MOEORBData = df_MOEORBData.to_numpy()[:, :input_size]
    stampObser = df_stampObser.to_numpy()
    stampMOEORB = df_stampMOEORB.to_numpy()

    data_size = ObserData.shape[0] // config.training_length
    ObserData = np.array(ObserData).reshape([data_size, config.training_length, input_size])
    MOEORBData = np.array(MOEORBData).reshape([data_size, config.training_length, input_size])
    stampObser = np.array(stampObser).reshape([data_size, config.training_length, config.fixStampSize])
    stampMOEORB = np.array(stampMOEORB).reshape([data_size, config.training_length, config.fixStampSize])

    noiceMOE = np.empty((0,5))
    List = range(data_size)
    t_bar = tqdm(List,total=len(List))
    for i in t_bar:
        res = calculate_noise(ObserData[i,:,0])
        new_data = np.array([[res[1]['std'], res[1]['mean'], res[1]['acf1'], res[1]['skewness'], res[1]['kurtosis']]])
        noiceMOE = np.concatenate((noiceMOE,new_data),axis=0)

    print(noiceMOE.shape)
    df_noiceMOE = pd.DataFrame(noiceMOE, columns=['std','mean','acf1','skewness','kurtosis'])
    df_noiceMOE.to_csv(config.saveDir+'df_noiceMOE.csv', index=False)